//
//  VideoFilterViewController.m
//  VideoDemo
//
//  Created by wangxue on 16/9/12.
//  Copyright © 2016年 dfl. All rights reserved.
//

#import "VideoFilterViewController.h"
#import "Constants.h"
#import "UtilFileCache.h"

@interface VideoFilterViewController ()

//摄像头
@property (nonatomic) GPUImageVideoCamera *videoCamera;
//滤镜
@property (nonatomic) GPUImageOutput<GPUImageInput> *filter;
//录制器
@property (nonatomic) GPUImageMovieWriter *movieWriter;

//
@property (nonatomic) GPUImageView *filterView;

//定时器 6秒自动录完
@property (nonatomic) NSTimer *timer;

//存mov格式的URL
@property (nonatomic) NSURL *movieURL;

//存mp4格式的URL
@property (nonatomic) NSURL *movieMP4URL;

//播放按钮
@property (nonatomic) UIButton *videoBtn;

//进度条进度
@property (nonatomic) UIView *presentProgress;

//取消按钮
@property (nonatomic) UIButton *cancelBtn;

//改变摄像头
@property (nonatomic) UIButton *cameraBtn;

@property (nonatomic) NSString *appName;


@property (nonatomic) BOOL isFont;



@end

@implementation VideoFilterViewController

#pragma mark - 生命周期

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    // app名称
    self.appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    if (!self.appName) self.appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
    
    
    if (![self PhotosjudgeIsHaveCameraAuthority] || ![self CameraAutorityRecordPermisson]){
        
        self.view.backgroundColor = [UIColor whiteColor];
        UIButton *warningLabe = [UIButton buttonWithType:UIButtonTypeCustom];
        warningLabe.titleLabel.numberOfLines = 0;
        [warningLabe setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [warningLabe setTitle:[NSString stringWithFormat:@"请在iPhone的设置-隐私->允许%@访问你的相机和麦克风",self.appName] forState:UIControlStateNormal];
        warningLabe.frame = self.view.frame;
        [self.view addSubview:warningLabe];
        [warningLabe addTarget:self action:@selector(setingBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        //
        UIButton *cancelLabe = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelLabe setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cancelLabe setTitle:@"取消" forState:UIControlStateNormal];
        [cancelLabe.titleLabel setTextAlignment:NSTextAlignmentLeft];
        [cancelLabe addTarget:self action:@selector(cancelVideo:) forControlEvents:UIControlEventTouchUpInside];
        [warningLabe addSubview:cancelLabe];
        [cancelLabe mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.width.height.mas_equalTo(60);
            
        }];
    }else {
        
        self.view.backgroundColor = [UIColor colorWithRed:38/255.0 green:38/255.0 blue:38/255.0 alpha:1];
        ;
        
        _filterView = [[GPUImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _filterView.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;
        [self.view addSubview:_filterView];
        [_filterView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(60);
            make.bottom.mas_equalTo(-100);
            make.left.right.mas_equalTo(0);
        }];
        
        _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:CGSizeMake(480.0, 640.0)];
        _movieWriter.encodingLiveVideo = YES;
        
        //    [self.videoCamera addTarget:self.filter];
        //    [self.filter addTarget:_movieWriter];
        //    [self.filter addTarget:filterView];
        
        [self.videoCamera addTarget:_filterView];
        [self.videoCamera addTarget:_movieWriter];
        
        if ([self allIsEmpty:self.albumName])
        {
            self.albumName = self.appName;
        }
        if (!self.maxRecorderTime)
        {
            self.maxRecorderTime = 6;
        }
        [self.videoCamera startCameraCapture];
        
        [self videoBtn];
        [self cancelBtn];
        [self cameraBtn];
        
    }
    
}

- (void)setingBtn:sender {
    
    if (IOS_VERSION_8_OR_ABOVE) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    } else {
        // 私有API上线会被拒
        //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]];
    }
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.isFont = YES;
    [self.videoCamera startCameraCapture];
    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isStart"];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.videoCamera stopCameraCapture];
    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isStart"];
    
    self.isFont = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

{
    // Map UIDeviceOrientation to UIInterfaceOrientation.
    UIInterfaceOrientation orient = UIInterfaceOrientationPortrait;
    switch ([[UIDevice currentDevice] orientation])
    {
        case UIDeviceOrientationLandscapeLeft:
            orient = UIInterfaceOrientationLandscapeLeft;
            break;
            
        case UIDeviceOrientationLandscapeRight:
            orient = UIInterfaceOrientationLandscapeRight;
            break;
            
        case UIDeviceOrientationPortrait:
            orient = UIInterfaceOrientationPortrait;
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            orient = UIInterfaceOrientationPortraitUpsideDown;
            break;
            
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
        case UIDeviceOrientationUnknown:
            // When in doubt, stay the same.
            orient = fromInterfaceOrientation;
            break;
    }
    self.videoCamera.outputImageOrientation = orient;
    
}


- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
#pragma mark - 方法

- (void)start_stop:(UIButton *)sender {
    sender.selected = !sender.selected;
    NSNumber *isStartn = [[NSUserDefaults  standardUserDefaults] objectForKey:@"isStart"];
    BOOL isStart = [isStartn boolValue];
    if (isStart) {
        [self startVideo:sender];
    }else{
        [self saveVideo:sender];
    }
    isStart = !isStart;
    [[NSUserDefaults standardUserDefaults] setObject:@(isStart) forKey:@"isStart"];
    
}

- (void)startVideo:sender {
    
    self.cameraBtn.hidden = YES;
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    [filemanager removeItemAtURL:self.movieURL error:nil];
    
    
    
    _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:CGSizeMake(480.0, 640.0)];
    [self.videoCamera addTarget:_movieWriter];
    [self.videoCamera addTarget:_filterView];
    //         [self.filter addTarget:_movieWriter];
    self.videoCamera.audioEncodingTarget = _movieWriter;
    
    
    
    [_movieWriter startRecording];
    [self recordProgress];
    
    
    _timer =  [NSTimer scheduledTimerWithTimeInterval:self.maxRecorderTime target:self selector:@selector(recordTime) userInfo:nil repeats:NO];
    
}

- (void)recordProgress{
    
    [self.view addSubview:self.presentProgress];
    [self.presentProgress mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-100);
        make.centerX.mas_equalTo(0);
        make.height.mas_equalTo(2);
        
        
    }];
    [self.view layoutIfNeeded];
    
    
    [UIView animateKeyframesWithDuration:self.maxRecorderTime delay:0 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{
        [self.presentProgress mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.height.mas_equalTo(2);
            make.width.mas_equalTo(1);
            make.bottom.mas_equalTo(-100);
        }];
        [self.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        [self.presentProgress removeFromSuperview];
    }];
}

- (void)recordTime {
    
    //
    self.videoBtn.selected = NO;
    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isStart"];
    
    [self saveVideo:self.videoBtn];
}


- (void)cancelVideo:sender {
    
    [_movieWriter cancelRecording];
    [_timer invalidate];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)changeCamera:sender {
    
    [_movieWriter cancelRecording];
    //    [self.filter removeTarget:_movieWriter];
    //    [self.videoCamera removeTarget:self.filter];
    [self.videoCamera removeAllTargets];
    self.videoCamera.audioEncodingTarget = nil;
    
    [self.videoCamera stopCameraCapture];
    self.videoCamera = nil;
    
    if (self.isFont){
        self.videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionFront];
        self.videoCamera.horizontallyMirrorFrontFacingCamera = YES;
        
    }else{
        
        self.videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
        self.videoCamera.horizontallyMirrorFrontFacingCamera = YES;
    }
    //输出图像旋转方式
    self.videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    
    //该句可防止允许声音通过的情况下 避免录制第一帧黑屏闪屏
    [self.videoCamera addAudioInputsAndOutputs];
    
    _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:CGSizeMake(480.0, 640.0)];
    //    [self.filter addTarget:_movieWriter];
    [self.videoCamera addTarget:_movieWriter];
    [self.videoCamera addTarget:_filterView];
    self.videoCamera.audioEncodingTarget = _movieWriter;
    
    [self.videoCamera startCameraCapture];
    
    self.isFont = !self.isFont;
    
}

- (void)saveVideo:sender {
    
    [_timer invalidate];
    
    [self.presentProgress removeFromSuperview];
    self.cameraBtn.hidden = NO;
    self.videoBtn.userInteractionEnabled = NO;
    
    //[_movieWriter finishRecording];
    
    [_movieWriter finishRecordingWithCompletionHandler:^{
        
        [self.videoCamera removeTarget:_movieWriter];
        self.videoCamera.audioEncodingTarget = nil;
        
        // 缓存到沙盒不写入相册
        if (self.cacheMovieKey) {
            [self exportVideoToCache];
            return; // 停掉
        }
        
        if (![self PhotosjudgeIsHavePhotoAblumAuthority] ){
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请在iPhone的设置-隐私->允许%@访问你的照片",self.appName] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                self.videoBtn.userInteractionEnabled = YES;
                
                if (IOS_VERSION_8_OR_ABOVE) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                } else {
                    // 私有API上线会被拒
                    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]];
                }
                
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:sureAction];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
            return;
            
        }
        
        [self SavePhoneAlbum];
    }];
    
    //
    //                       [_videoCamera.inputCamera lockForConfiguration:nil];
    //                    [_videoCamera.inputCamera setTorchMode:AVCaptureTorchModeOn];
    //                    [_videoCamera.inputCamera unlockForConfiguration];
    
    //
    //    });
}

//压缩视频
- (void) lowQuailtyWithInputURL:(NSURL*)inputURL
                      outputURL:(NSURL*)outputURL
                   blockHandler:(void (^)(AVAssetExportSession*))handler
{
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset     presetName:AVAssetExportPresetHighestQuality];
    session.outputURL = outputURL;
    session.outputFileType = AVFileTypeQuickTimeMovie;
    [session exportAsynchronouslyWithCompletionHandler:^(void)
     {
         if (handler) {
             handler(session);
         }
     }];
}

- (void)exportVideoToCache {
    NSString *cacheKey = self.cacheMovieKey;
    UtilFileCache *fileCache = [UtilFileCache instance];
    NSURL *outputURL = [NSURL fileURLWithPath:[fileCache cachePathForKey:cacheKey]];
    [self lowQuailtyWithInputURL:self.movieURL outputURL:outputURL blockHandler:^(AVAssetExportSession *session) {
        if (self.completBlock) {
            self.completBlock(outputURL);
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

- (void)saveVideoToCache {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *cacheKey = self.cacheMovieKey;
        UtilFileCache *fileCache = [UtilFileCache instance];
        NSError *error;
        [fileCache.fileManager copyItemAtPath:self.movieURL.path toPath:[fileCache cachePathForKey:cacheKey] error:&error];
        if (error) {
            NSLog(@"save Video Failure%@", error);
            if (self.completBlock) {
                self.completBlock(nil);
            }
        } else {
            if (self.completBlock) {
                self.completBlock([NSURL fileURLWithPath:[fileCache cachePathForKey:cacheKey]]);
            }
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    });
}

- (void)SavePhoneAlbum {
    
    
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    
    [library saveVideo:self.movieURL toAlbum:self.albumName completion:^(NSURL *assetURL, NSError *error) {
        
        /* [self movieToImageWithMediaURL:assetURL AndHander:^(UIImage *movieImage) {
         
         if (self.completBlock) {
         
         self.completBlock(assetURL, movieImage);
         }
         
         
         }];*/
        if (self.completBlock) {
            
            self.completBlock(assetURL);
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(NSError *error) {
        if (error) {
            NSLog(@"save Video Failure%@", error);
        }
    }];
    
}


//获取视频第一帧图片
- (void)movieToImageWithMediaURL:(NSURL *)mediaURL AndHander:(void(^)(UIImage *movieImage))hander {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:mediaURL options:nil];
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform = TRUE;
    CMTime thumbTime = CMTimeMakeWithSeconds(0, 60);
    generator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    AVAssetImageGeneratorCompletionHandler generatorHandler =
    ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
        if (result == AVAssetImageGeneratorSucceeded) {
            UIImage *thumbImg = [UIImage imageWithCGImage:im];
            
            if (hander) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    hander(thumbImg);
                });
            }
        }
    };
    [generator generateCGImagesAsynchronouslyForTimes:
    [NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:generatorHandler];
    
}
//相册使用权限
- (BOOL)PhotosjudgeIsHavePhotoAblumAuthority {
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    ALAuthorizationStatus state = [ALAssetsLibrary authorizationStatus];
    // 家长控制,不允许访问    用户拒绝当前应用访问相册,我们需要提醒用户打开访问开关
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        return NO;
    }else if (state == ALAuthorizationStatusRestricted || state == ALAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}
//相机使用权限
- (BOOL)PhotosjudgeIsHaveCameraAuthority
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted ||
        status == AVAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

//麦克风
- (BOOL)CameraAutorityRecordPermisson
{
    
    __block  BOOL isAllow;
    //麦克风
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        isAllow = granted;
    }];
    return isAllow;
}


#pragma mark - 懒加载

- (UIButton *)videoBtn {
    
    if (!_videoBtn) {
        
        _videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *imagePathInControllerBundlePlay = [NSString stringWithFormat:@"YuanXinCamera.bundle/%@", @"play"];
        NSString *imagePathInControllerBundleStop = [NSString stringWithFormat:@"YuanXinCamera.bundle/%@", @"stop"];
        [_videoBtn setImage:[UIImage imageNamed:imagePathInControllerBundlePlay] forState:UIControlStateNormal];
        [_videoBtn setImage:[UIImage imageNamed:imagePathInControllerBundleStop] forState:UIControlStateSelected];
        _videoBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        _videoBtn.layer.borderWidth = 1.0;
        _videoBtn.layer.cornerRadius = 40;
        [self.view addSubview:_videoBtn];
        [_videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(80, 80));
            make.bottom.mas_equalTo(-10);
        }];
        [_videoBtn addTarget:self action:@selector(start_stop:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _videoBtn;
}

- (GPUImageVideoCamera *)videoCamera {
    
    if (!_videoCamera) {
        
        _videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
        //输出图像旋转方式
        _videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        _videoCamera.horizontallyMirrorFrontFacingCamera = YES;
        
        //该句可防止允许声音通过的情况下 避免录制第一帧黑屏闪屏
        [_videoCamera addAudioInputsAndOutputs];
    }
    
    return _videoCamera;
}
//
- (GPUImageOutput<GPUImageInput> *)filter {
    
    if (!_filter)
    {
        _filter = [[GPUImageCropFilter alloc] initWithCropRegion:CGRectMake(0.0, 0.0, 1.0, 1.0)];
        //[(GPUImageSketchFilter *)_filter setIntensity:0];
    }
    return _filter;
}
//
- (NSURL *)movieURL {
    
    if (!_movieURL)
        
    {
        NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:self.appName];
        //创建用户文件夹
        [[NSFileManager defaultManager] createDirectoryAtPath:Path withIntermediateDirectories:YES attributes:nil error:nil];
        
        NSString *pathToMoview =  [ Path stringByAppendingPathComponent:@"Movie.mov"];
        
        unlink([pathToMoview UTF8String]); // If a file already exists, AVAssetWriter won't let you record new frames, so delete the old movie
        _movieURL = [NSURL fileURLWithPath:pathToMoview];
        
        
        
    }
    return _movieURL;
}

- (UIView *)presentProgress {
    
    if (!_presentProgress){
        _presentProgress = [UIView new];
        _presentProgress.backgroundColor = [UIColor greenColor];
        [self.view addSubview:_presentProgress];
        [_presentProgress mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(-100);
            make.centerX.mas_equalTo(0);
            make.height.mas_equalTo(2);
        }];
    }
    return _presentProgress;
}

- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelVideo:) forControlEvents:UIControlEventTouchUpInside];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [self.view addSubview:_cancelBtn];
        [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.bottom.mas_equalTo(self.view.mas_top).mas_equalTo(60);
        }];
    }
    return _cancelBtn;
}

- (UIButton *)cameraBtn {
    
    if (!_cameraBtn)
    {
        _cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSBundle *bundel = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YuanXinCamera" ofType:@"bundle"]];
        NSString *path = [bundel pathForResource:@"changeCamer" ofType:@"png"];
        
        [_cameraBtn setBackgroundImage:[UIImage imageWithContentsOfFile:path] forState:UIControlStateNormal];
        
        _cameraBtn.clipsToBounds = YES;
        [self.view addSubview:_cameraBtn];
        [_cameraBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-10);
            make.bottom.mas_equalTo(self.cancelBtn.mas_bottom).mas_equalTo(-5);
            make.size.mas_equalTo(CGSizeMake(30, 30));
        }];
        
        [_cameraBtn addTarget:self action:@selector(changeCamera:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _cameraBtn;
}

- (BOOL)allIsEmpty:(NSString *) str;
{
    
    if (!str) {
        return true;
    } else {
        
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}




@end
